<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

//使用类
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Crypt;
//模型
use App\Admin;

//后台登录控制器
class LoginController extends Controller
{
    //后台登录首页
	public function index(Request $request){

        $request->session()->forget('lenovoAdminUserInfo');//退出登录

        return view("admin.login");
	}

	//验证码
    public function yzm(){
	    //引入验证码类文件
        require_once("../resources/code/Code.class.php");

        //实例化
        $code= new \Code();

        //生成验证码
        $code->make();

    }

    //处理请求
    public function check(Request $request){
        //dd($request->all());
        $name= $request->input('name');
        $pass= $request->input('pass');
        $ucode= $request->input('code');

        //验证验证码
        require_once("../resources/code/Code.class.php");

        //实例化
        $code= new \Code();
        //获取session
        $ocode = $code->get();

        //echo $ocode;
        //监测验证码
        if(strtoupper($ucode)==$ocode){
            //验证密码
            $data = Admin::where([["name","=","$name"],["status","=",0]])->first();//first()返回在数据库中找到的第一条记录。如果不存在匹配的模型，则返回null。
//dd($data);
            if($data){
                if($pass == Crypt::decrypt($data->pass)){
                    //声明数组
                    $arr=[];
                    $arr['lasttime']=time();
                    $arr['count']= ++$data->count;

                    //更新登录信息
                    Admin::where('id',$data->id)->update($arr);

                    //存session
                    //session(['lenovoAdminUserInfo.name'=>$data->name]);
                    //session(['lenovoAdminUserInfo.id'=>$data->id]);
                    $newArr=[];
                    $newArr['name']= $data->name;
                    $newArr['id']= $data->id;
                    session(['lenovoAdminUserInfo' => $newArr]);

                    //跳转到首页
                    return redirect('admin');

                }else{
                    return back()->with("error","密码错误");
                }
            }else{
                return back()->with("error","用户名不存在");
            }

        }else{
            return back()->with("error","验证码错误");
        }

    }

    //退出
    public function logout(Request $request){

        $request->session()->flush();
        return redirect('admin/login');
    }


}
